package cn.itcast.lucene;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.search.highlight.*;
import org.apache.lucene.search.highlight.Scorer;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;

public class LuceneIndexSuperQuery {


    @Test
    public void testSuperQuery() throws IOException, ParseException, InvalidTokenOffsetsException {


        //找到索引的地址
        Directory directory = FSDirectory.open(new File("indexDir"));

        //创建索引的读取对象
        IndexReader indexReader = DirectoryReader.open(directory);

        //创建搜索对象
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);


        QueryParser queryParser = new QueryParser("title", new IKAnalyzer());


        Query query = queryParser.parse("谷歌地图");


        //search，两个参数分别表示查询条件对象以及要查询的个数（前n条 topN）
        //执行查询，返回前n条文档数据集合
        TopDocs search = indexSearcher.search(query, Integer.MAX_VALUE);

        //命中的条目数
        int totalHits = search.totalHits;

        System.out.println("totalHits = " + totalHits);

        //所有的得分文档数组
        ScoreDoc[] scoreDocs = search.scoreDocs;

        //创建高亮的工具

        Formatter formatter = new SimpleHTMLFormatter("<em>", "</em>");

        Scorer scorer = new QueryScorer(query);

        Highlighter highlighter = new Highlighter(formatter, scorer);

        for (ScoreDoc scoreDoc : scoreDocs) {
            //得分
            float score = scoreDoc.score;

            //文档ID
            int docID = scoreDoc.doc;

            //根据文档的id找到对应的文档
            Document document = indexSearcher.doc(docID);


            String id = document.get("id");
            String oldTitle = document.get("title");

            //使用高亮工具对查询到的普通结果进行分词，
            String highlighterTitle = highlighter.getBestFragment(new IKAnalyzer(), "title", oldTitle);

            System.out.println("得分： " + score + " id:" + id + " title:" + highlighterTitle);
        }

    }


    @Test
    public void testSortQuery() throws IOException, ParseException, InvalidTokenOffsetsException {


        //找到索引的地址
        Directory directory = FSDirectory.open(new File("indexDir"));

        //创建索引的读取对象
        IndexReader indexReader = DirectoryReader.open(directory);

        //创建搜索对象
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);


        QueryParser queryParser = new QueryParser("title", new IKAnalyzer());


        Query query = queryParser.parse("谷歌地图");

        Sort sort = new Sort(new SortField("id", SortField.Type.LONG, true));


        //search，两个参数分别表示查询条件对象以及要查询的个数（前n条 topN）
        //执行查询，返回前n条文档数据集合
        TopDocs search = indexSearcher.search(query, Integer.MAX_VALUE, sort);

        //命中的条目数
        int totalHits = search.totalHits;

        System.out.println("totalHits = " + totalHits);

        //所有的得分文档数组
        ScoreDoc[] scoreDocs = search.scoreDocs;


        for (ScoreDoc scoreDoc : scoreDocs) {
            //得分
            float score = scoreDoc.score;

            //文档ID
            int docID = scoreDoc.doc;

            //根据文档的id找到对应的文档
            Document document = indexSearcher.doc(docID);


            String id = document.get("id");
            String oldTitle = document.get("title");

            System.out.println("得分： " + score + " id:" + id + " title:" + oldTitle);
        }

    }


    @Test
    public void testPageQuery() throws IOException, ParseException, InvalidTokenOffsetsException {


        int currentPage = 4;
        final int PAGE_SIZE = 2;
        int start = (currentPage - 1) * PAGE_SIZE;//4
        int end = currentPage * PAGE_SIZE;//6
        int total = -1;
        int totalPage = -1;


        //找到索引的地址
        Directory directory = FSDirectory.open(new File("indexDir"));

        //创建索引的读取对象
        IndexReader indexReader = DirectoryReader.open(directory);

        //创建搜索对象
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);


        QueryParser queryParser = new QueryParser("title", new IKAnalyzer());


        Query query = queryParser.parse("谷歌地图");

        Sort sort = new Sort(new SortField("id", SortField.Type.LONG));


        //search，两个参数分别表示查询条件对象以及要查询的个数（前n条 topN）
        //执行查询，返回前n条文档数据集合
        TopDocs search = indexSearcher.search(query, Integer.MAX_VALUE, sort);

        //命中的条目数
        int totalHits = search.totalHits;

        System.out.println("totalHits = " + totalHits);

        //所有的得分文档数组
        ScoreDoc[] scoreDocs = search.scoreDocs;

        total = scoreDocs.length;

        totalPage = total % PAGE_SIZE == 0 ? total / PAGE_SIZE : total / PAGE_SIZE + 1;

        if (currentPage>totalPage){
            System.out.println("当前页太大没这么多，总共："+totalPage+" 页");
            return;
        }else if(currentPage==totalPage){
            end = total;
            //6    6
        }


        for (int i = start; i < end; i++) {//5  4

            ScoreDoc scoreDoc = scoreDocs[i];

            //得分
            float score = scoreDoc.score;

            //文档ID
            int docID = scoreDoc.doc;

            //根据文档的id找到对应的文档
            Document document = indexSearcher.doc(docID);


            String id = document.get("id");
            String oldTitle = document.get("title");

            System.out.println("得分： " + score + " id:" + id + " title:" + oldTitle);
        }


    }
}
